/**
 * Define your components
 */
// For 404 page
$(function () {
  const notFound = {
    template: '#test_scroller'
  }
  //axios.defaults.timeout =  6000;
  axios.interceptors.request.use(function(config){
    //在发送请求之前做某事，比如说 设置loading动画显示
    $.showLoading('请稍等...')
    return config
  }, function(error){
    //请求错误时做些事
     $.hideLoading('请稍等...')
    return Promise.reject(error)
  })

  //添加响应拦截器
  axios.interceptors.response.use(function(response){
    //对响应数据做些事，比如说把loading动画关掉
    $.hideLoading('请稍等...')
    return response
  }, function(error) {
    //请求错误时做些事
    $.hideLoading('请稍等...')
    return Promise.reject(error)
  })

  Vue.prototype.$http = axios
  const set_title = function (tilte) {
    document.title = tilte
  }
  Vue.directive('longtouch', function (el, binding) { //自定义 长按 弹出菜单选项
    var oDiv = el,
      value = binding.value,
      x = 0, y = 0, z = 0, timer = null
    oDiv.addEventListener('touchstart', function (e) {
      if (e.touches.length > 1) {
        return false
      }
      z = 0
      timer = setTimeout(function () {
        z = 1
      }, 300)
      x = e.touches[0].clientX
      y = e.touches[0].clientY
      e.preventDefault()
    }, false)
    document.addEventListener('touchmove', function (e) {
      if (x != e.touches[0].clientX || y != e.touches[0].clientY) {
        clearTimeout(timer)
        return false
      }
    }, false)
    document.addEventListener('touchend', function (ev) {
      if (z != 1) {
        clearTimeout(timer)
        x = 0
        y = 0
        return false
      } else {
        x = 0
        y = 0
        z = 0
        if (value.length > 0) {
          $.actions({
            onClose: function () {
            },
            actions: value
          })
        }
      }
    }, false)
  })

  // Vue.http.interceptors.request.use(function (request, next) {
  //   $.showLoading('请稍等...')
  //   next(function (response) {
  //     $.hideLoading('请稍等...')
  //     return response
  //   })
  // })
  const toast_success = {
    props: {success_msg: String},
    template: '#toast_success',
    data: function () {
      return {success_msg: 'hello'}
    },
  }

  Vue.component('toast-success', toast_success)
  Vue.filter('length', function (value) {
    if (value == null) return 0
    if (typeof value != 'string') {
      value += ''
    }
    return value.length
  })

  const gridsViews = {
    //props: ['img_src', 'new_page', 'show_str'],
    template: '#vue_grid',
    // 技术上 data 的确是一个函数了，因此 Vue 不会警告，
    // 但是我们返回给每个组件的实例的却引用了同一个data对象
    data: function () {
      return {
        all_grid: [{
          new_page: 'new_ask_for_leave',
          link: {'path': '/allopereation', params: {type: 'work'}},
          img_src: '/dftg_weixin/static/src/img/leave.png',
          type: 'work',
          show_str: '加班',
          path: '/404',
        },
          {
            new_page: '/allopereation/leave',
            link: {'path': '/allopereation', params: {type: 'leave'}},
            img_src: '/dftg_weixin/static/src/img/change.png',
            show_str: '调休',
            type: 'leave',
            path: '/404',
          }]
      }
    },
    created: function () {
      set_title('主页')
    },
  }
  Vue.component('vue_input_val', {
    props: ['required', 'value', 'pattern', 'str', 'disabled', 'type_detail', 'required_error', 'index'],
    template: '#vue_input_component',
    data: function () {
      return {
        input_required: this.required,
        input_pattern: this.pattern,
        input_str: this.str,
        input_disabled: this.disabled,
        input_type_detail: this.type_detail,
        input_required_error: this.required_error,
      }
    },
    computed: {
      input_value: {
        get: function () {
          return this.value
        },
        set: function (v) {
          this.$emit('update:value', v)
        }
      }
    },
    watch: {
      // 如果 question 发生改变，这个函数就会运行
      input_required: function (newvalue) {
        this.$emit('update:required', newvalue)
      },
      input_type_detail: function (newvalue) {
        this.$emit('update:type_detail', newvalue)
      },
      input_disabled: function (newvalue) {
        this.$emit('update:disabled', newvalue)
      },
      input_pattern: function (newvalue) {
        this.$emit('update:pattern', newvalue)
      },
      input_str: function (newvalue) {
        this.$emit('update:str', newvalue)
      },
      input_required_error: function (newvalue) {
        this.$emit('update:required_error', newvalue)
      },
    },
  })

  // const viewAllOperation = {
  //     template: '#vue_cells',
  //     data: function () {
  //         var router_type = this.$route.params.type
  //         return {
  //             show_num: 0,
  //             all_operation: [
  //                 {
  //                     str: router_type == 'work' ? '申请加班' : '申请调休',
  //                     link: {path: '/allopereation/newleaveform', params: {type: router_type}}
  //                 },
  //                 {
  //                     str: '未审核', link: {
  //                     path: '/allopereation/treeFormView',
  //                     params: {approve_type: 'unapprove', type: router_type}
  //                 }
  //                 },
  //                  {
  //                     str: '已审核', link: {
  //                     path: '/allopereation/treeFormView',
  //                     params: {approve_type: 'approve', type: router_type}
  //                 }
  //                 },
  //                 {
  //                     str: router_type == 'work' ? '我的加班' : '我的调休',
  //                     link: {
  //                         path: '/allopereation/treeFormView',
  //                         params: {type: router_type, approve_type: 'all'}
  //                     }
  //                 },
  //             ]
  //         }
  //     },
  //     created: function () {
  //         var url = "/wx/hr/get_unapprove_num_ask_leave";
  //         var show_num = 0;
  //         this.$http.get(url, {params: {type: this.$route.params.type}}).then(function (res) {
  //             this.show_num = res.body;
  //         });
  //         set_title(this.$route.params.type == 'work' ? '加班' : '调休')
  //     },
  //
  // };

  const detialFormView = {
    template: '#vue_form_detail',
    data: function () {
      return {
        html_type: 'normal',
        success_msg: '',
        is_inital_data: true,
        all_fields: '',
        last_start_time: '',
        last_end_time: '',
        last_hours: '',
        loading: true,
        required_error: '',
        error_show: false,
        page_msg: false,

      }
    },
    created: function () {
      this.loading = true
      var url = '/wx/hr/get_ask_leave_fields'
      var self = this;
      this.$http.get(url, {
        params: {
          type: this.$route.params.type,
          id: this.$route.params.id
        }
      }).then(function (res) {
        self.loading = false
        self.all_fields = self.handle_the_data(res.data)
      })
      set_title('新建' + (this.$route.params.type == 'work' ? '加班' : '调休'))
    },
    methods: {
      handle_the_data: function (data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].type_detail == 'datetime-local') {
            data[i].value = moment(data[i].value).format('YYYY-MM-DDTHH:mm')
          } else if (data[i].type_detail == 'number') {
            data[i].value = parseFloat(data[i].value || '')
          } else if (data[i].type_detail == 'input') {
          }
        }
        return data
      },
      add_new_record: function (event) {
        var submit_fields = ''
        try {
          var new_record_url = '/wx/hr/new_ask_for_leave'
          var return_flag = false
          submit_fields = JSON.parse(JSON.stringify(this.all_fields))
          for (var index = 0; index < this.all_fields.length; index++) {
            if (this.all_fields[index].required && !this.all_fields[index].value) {
              this.required_error = true
              $.toptips('请输入' + this.all_fields[index].str)
              return true
            }
            if (this.all_fields[index].type_detail == 'datetime-local') {
              var value = this.all_fields[index].value
              var date_val = value.split(/[^0-9]/)
              var now = new Date(date_val[0], date_val[1] - 1, date_val[2], date_val[3], date_val[4]).toISOString()
              submit_fields[index].value = now
            }
          }
          if (this.all_fields[3].value <= 0) {
            $.toptips((this.$route.params.type == 'work' ? '请假' : '调休') + '时间必须大于零')
            return
          }
          if (this.$route.params.type == 'leave') {
            var leave_hours = this.all_fields[3].value
            var range_vals = this.all_fields[5].value_range

            var reconcile_hour = _.reduce(this.all_fields[5].value, function (memo, num) {
              console.log(range_vals[num], 'range_vals[num]');
              return range_vals[num].hours + memo
            }, 0)
            // if (leave_hours > reconcile_hour) {
            //   $.toptips('勾选的调休时间不够抵扣！')
            //   return
            // }
          }
          var self = this;
          this.$http.post(new_record_url, // 请求体重发送数据给服务端
            {all_fields: submit_fields, model_type: this.$route.params.type}).then(function (data) {
            if (data.data && JSON.parse(data.data.result).errMsg) {
              $.toptips(JSON.parse(data.data.result).errMsg)
            } else if(data.data.result &&  JSON.parse(data.data.result).create_id) {
              self.page_msg = true
              self.html_type = 'success'
            }else {
              $.toptips("新建错误，请联系管理员")
            }
          }, function (error) {
              $.toptips("请求超时请重试！如重试还不行，请联系管理员！")
              // alert('错误' + JSON.stringify(error) )
          }).catch(function (error) {
            $.toptips(" ！" + JSON.stringify(error))
          }); 
        } catch (err) {
          alert('错误' + JSON.stringify(err) + '' + JSON.stringify(this.all_fields))
        }

      }
    },
    watch: {
      all_fields: {
        handler: function (val, oldVal) {
          if ((val[1].value && val[2].value) && (val[1].value != this.last_start_time || val[2].value != this.last_end_time)) {
            this.last_start_time = val[1].value
            this.last_end_time = val[2].value
            var begin_date = new Date(this.last_start_time)
            var end_date = new Date(this.last_end_time)
            if (!this.is_inital_data) {
              this.all_fields[3].value = ((end_date.getTime() - begin_date.getTime()) / (60 * 60000)).toFixed(1)
            }else{
              this.is_inital_data = false
            }
          }
          if (val[3].value != this.last_hours) {
              this.last_hours = val[3].value;
              this.all_fields[3].value = this.last_hours;
          }
        },
        deep: true
      },
    }

  }

  const treeFormView = {
    template: '#container',
    data: function () {
      return {
        all_records: [],
        all_invisible: this.$route.params.approve_type == 'unapprove',
        success_msg: '',
        loading: true,
        offset: 0,
        locading_msg: '加载数据中',
        now_record_length: 0,
        is_all_records_data: true,
      }
    },
    created: function () {
      this.get_all_records()
      var type_str = (this.$route.params.type == 'work' ? '加班' : '调休')
      var approve_str = this.$route.params.approve_type == 'unapprove' ? '待审核' : ''
      set_title(approve_str + type_str + '列表')
    },
    watch: {
      '$route': function (to, from) {
        var type_str = (this.$route.params.type == 'work' ? '加班' : '调休')
        var approve_str = this.$route.params.approve_type == 'unapprove' ? '待审核' : ''
        set_title(approve_str + type_str + '列表')
        this.all_invisible = this.$route.params.approve_type == 'unapprove'
        this.get_all_records()
      },
    },
    methods: {
      approver_work_or_leave: function (record_id, index) {
        var new_record_url = '/wx/hr/approver_work_or_leave'
        var self = this;
        this.$http.post(new_record_url, // 请求体重发送数据给服务端
          {
            record_id: record_id
          }).then(function () {
          self.all_records.splice(index, index + 1)
          self.success_msg = '审核通过'
          self.refresh_show_num()
          var $toast = $('#toast')
          if ($toast.css('display') != 'none') return
          $toast.fadeIn(100)
          setTimeout(function () {
            $toast.fadeOut(100)
          }, 500)
        })
      },
      change_approver_work_or_leave: function (record) {
        this.$router.push({
          name: 'form',
          params: {
            type: this.$route.params.type,
            id: record[0].value,
          }
        })
      },
      longtouch_tree: function (index, record) {
        var all_records = this.all_records
        var self_post = this.$http
        var delete_record_url = '/wx/hr/delete_work_or_leave'
        if (this.$route.params.approve_type === 'all' && record[1].value !== 1) {
          return [{
            text: '删除',
            className: 'color-danger',
            onClick: function () {
              all_records.splice(index, index + 1)
              self_post.post(delete_record_url, {record_id: record[0].value})
              $.toast('删除成功!')
            }
          }]
        } else {
          return []
        }
      },
      refresh_show_num: function () {
        var url = '/wx/hr/get_unapprove_num_ask_leave'
        var self = this;
        this.$http.get(url, {params: {type: this.$route.params.type}}).then(function (res) {
          self.$root.show_num = res.data
        })
      },

      refuse_work_or_leave: function (record_id, index) {
        var new_record_url = '/wx/hr/refuse_work_or_leave'
        var self = this;
        this.$http.post(new_record_url, // 请求体重发送数据给服务端
          {
            record_id: record_id
          }).then(function () {
          self.all_records.splice(index, index + 1)
          self.success_msg = '拒绝'
          self.refresh_show_num()
          var $toast = $('#toast')
          if ($toast.css('display') != 'none') return
          $toast.fadeIn(100)
          setTimeout(function () {
            $toast.fadeOut(100)
          }, 500)
        })
      },
      get_all_records: function () {
        var url = '/wx/hr/get_ask_for_leave'
        this.offset = 0
        var self = this;
        self.$http.get(url, {
          params: {
            type: this.$route.params.type,
            unapprove: this.$route.params.approve_type,
            offset: this.offset,
          }
        }).then(function (res) {
          self.now_record_length = res.data.length
          self.all_records = res.data
        })
      }
      ,
      refresh: function (done) {
        var self = this
        setTimeout(function () {
          self.get_all_records()
          done()
        }, 500)
      }
      ,
      infinite: function (done) {
        var self = this
        if (self.is_all_records_data || this.now_record_length < 4) {
          setTimeout(function () {
            done(true)
            self.is_all_records_data = false
          }, 500)
          return
        }

        setTimeout(function () {
          self.offset = self.offset + 4
          var url = '/wx/hr/get_ask_for_leave'
          self.$http.get(url, {
            params: {
              type: self.$route.params.type,
              unapprove: self.$route.params.approve_type,
              offset: self.offset,
            }
          }).then(function (res) {
            if (res.data.length != 4) {
              self.is_all_records_data = true
            } else {
              self.is_all_records_data = false
            }
            this.now_record_length = res.data.length
            self.all_records = self.all_records.concat(res.data)
          })
          self.bottom = self.bottom + 10
          done()
        }, 500)

      }
    },
  }

  // const routes = [
  //     {path: '*', component: notFound},
  //     //{path: '/', component: gridsViews},
  //     //{path: '/allopereation', component: viewAllOperation},
  //     {path: '/newleaveform', component: detialFormView},
  //     {path: '/treeFormView', component: treeFormView},
  // ]
  const exchange_url = {
    template: '#test_scroller',
    data: function () {
      return {
        all_records: [],
      }
    },
    created: function () {
      var path = window.location.pathname.split('/wx/hr/')

      var router_approve_type = path[1].split('/')
      this.$router.push({
        name: 'tree',
        params: {
          type: router_approve_type[0],
          approve_type: router_approve_type[1],
        }
      })
    },
  }

  const routes = [
    {path: '*', component: exchange_url},
    {path: '/newleaveform/:type/:id', component: detialFormView, name: 'form'},
    {path: '/treeFormView/:type/:approve_type', component: treeFormView, name: 'tree'},
  ]

  const router = new VueRouter({
    routes: routes, // （缩写）相当于 routes: routes
  })
  const app = new Vue({
    router: router,
    data: function () {
      return {
        router_type: router_type,
        show_num: 0,
        all_operation: []
      }
    },
    methods: {},
    watch: {
      '$route': function (to, from) {
        var url = '/wx/hr/get_unapprove_num_ask_leave';
        var self = this;
        this.$http.get(url, {params: {type: self.$route.params.type}}).then(function (res) {
          self.show_num = res.data
        })
        //var router_type = this.$route.params.type
      }
    },

    created: function () {
      var url = '/wx/hr/get_unapprove_num_ask_leave'
      var self = this;
      var router_type = this.router_type;
      this.$http.get(url, {params: {type: router_type}}).then(function (res) {
        self.show_num = res.data
      })
      set_title(router_type == 'work' ? '加班' : '调休')
      var url = '/wx/hr/get_unapprove_num_ask_leave'
      this.$http.get(url, {params: {type: router_type}}).then(function (res) {
        self.show_num = res.data
      })
      var router_type = router_type
      self.all_operation = [
        {
          str: router_type == 'work' ? '申请加班' : '申请调休',
          link: {name: 'form', params: {type: router_type}},
          img: '/dftg_weixin/static/src/img/icon_nav_button.png',

        },
        {
          str: '未审核',
          img: '/dftg_weixin/static/src/img/icon_nav_msg_unapprove.png',
          link: {
            name: 'tree',
            params: {
              approve_type: 'unapprove',
              type: router_type
            },

          }
        },
        {
          str: router_type == 'work' ? '我的加班' : '我的调休',
          img: '/dftg_weixin/static/src/img/icon_nav_article.png',
          link: {
            name: 'tree',
            params: {
              type: router_type,
              approve_type: 'all',
            }
          }
        },
      ]
      var group_leader = {
        str: '已审核',
        img: '/dftg_weixin/static/src/img/icon_nav_msg.png',
        link: {
          name: 'tree',
          params: {
            approve_type: 'approve',
            type: router_type
          }
        }
      }
      var group_hr = {
        str: '已审核',
        img: '/dftg_weixin/static/src/img/icon_nav_msg.png',
        link: {
          name: 'tree',
          params: {
            approve_type: 'other_approve',
            type: router_type
          }
        }
      }
      //
      var group_url = '/wx/hr/get_user_group_message';
      this.$http.get(group_url).then(function (res) {
        if (res.data == '0') {
          self.all_operation.splice(2, 0, group_hr)
        } else if (res.data == '1') {
          self.all_operation.splice(2, 0, group_leader)
        } else {

        }
      })
    },
  }).$mount('#leave_work')

})